//
//  HMStatusDAL.swift
//  sinaweibo
//
//  Created by WGP on 16/4/24.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

///数据访问层

/*
微博数据缓存流程:
    1.查看本地是否有保存数据
    2.如果本地有数据直接使用本地的数据
    3.本地没有数据,发送网络请求,去服务器加载
    4.将服务器返回的数据保存到本地
    5.再讲服务器返回的数据,返回给别人处理
*/

class HMStatusDAL: NSObject {
    
    static let sharedDAL: HMStatusDAL = HMStatusDAL()
    
    private let overtime: NSTimeInterval = 60 //一般是一个礼拜
    
    private override init() {
        super.init()
    }
    
    ///删除过期的微博数据
    func deleteCacheStatus()
    {
//        计算过期时间 
        let overDate = NSDate(timeIntervalSinceNow: -overtime)
        
        let df = NSDateFormatter()
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let overDateString = df.stringFromDate(overDate)
        
        
        let sql = "DELETE FROM T_Status WHERE createTime < '\(overDateString)'"
        HMSQLiteManager.sharedManager.dbQueue.inDatabase { (db) -> Void in
            
            do
            {
               try db.executeUpdate(sql, values: [])
                print("清除缓存成功")
                
            }catch let error as NSError
            {
                print("清除失败:\(error)")
            }
        }
    }
    
    func loadStatus(since_id: Int64, max_id: Int64, loadStatusCallBack:(status:[[String: AnyObject]]?, error: NSError?)->())
    {
//        1.查看本地数据库是否保存数据
        loadCacheStatus(since_id, max_id: max_id) { (status) -> () in
            if status != nil && status?.count > 0
            {
//                2.本地有数据直接使用本地数据
                print("从本地加载了数据")
                loadStatusCallBack(status: status,error: nil)
                return
            }
//            3.本地没有数据,发送网络请求,去服务器加载数据
            let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
            var parameters: [String: AnyObject] =
            [
               "access_token":(HMUserAccountViewModel.sharedInstance.userAccount?.access_token)!
            ]
            
            if since_id > 0
            {
                parameters["since_id"] = NSNumber(longLong: since_id)
                
            }else if max_id > 0
            {
//                返回ID小于或等于max_id的微博,不需要后的一条微博
                parameters["max_id"] = NSNumber(longLong: max_id-1)
            }
            
//            发送网络请求
            HMNetWorkTool.sharedInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
                
//                看能否转成字典,获取字典里面的内容
                if let dict = responseObject as? [String: AnyObject], let statusDict = dict["statuses"] as? [[String: AnyObject]]
                {
                    self.saveCacheStatus(statusDict)
                    
                    loadStatusCallBack(status: statusDict, error: nil)
                }
                
                }, failure: { (task, error) -> Void in
                    
                    loadStatusCallBack(status: nil, error: error)
            })
        }
    }
 
    ///本地数据库加载微博数据
    private func loadCacheStatus(since_id: Int64, max_id: Int64, loadCacheStatusCallBack:(status: [[String: AnyObject]]?)->())
    {
        let uid = HMUserAccountViewModel.sharedInstance.userAccount?.uid
        
        assert(uid != nil, "没有uid")
        
        var sql = "SELECT status_id, status, user_id FROM T_Status \n" + "WHERE user_id = \(uid!) \n"
        if since_id > 0
        {
//            下拉刷新
            sql += "AND status_id > \(since_id) \n"
        }else if max_id > 0
        {
//            上拉加载
            sql += "AND status_id < \(max_id) \n"
        }
        
        sql += "ORDER BY status_id DESC LIMIT 20"
        
        HMPrint("sql: \(sql)")
        
//        查询数据
        HMSQLiteManager
        .sharedManager.dbQueue.inDatabase { (db) -> Void in
            
            do
            {
                let resultSet = try db.executeQuery(sql, values: [])
                
//                定义字典保存数据库中家在的数据
                var statusDicts = [[String: AnyObject]]()
                
                while resultSet.next()
                {
                    let statusText = resultSet.stringForColumn("status")
                    
//                    返回的是数组
//                    String->Data->JSON
                    let data = statusText.dataUsingEncoding(NSUTF8StringEncoding)!
                    let statusDict = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as! [String: AnyObject]
                    
                    statusDicts.append(statusDict)
                }
//                将数据库加载的微博数据返回回去
                loadCacheStatusCallBack(status: statusDicts)
                
            }catch let error as NSError
            {
                print("加载微博数据出错了:\(error)")
                loadCacheStatusCallBack(status: nil)
            }
        }
    }
    
///    保存微博字典数据到数据库
    private func saveCacheStatus(status: [[String: AnyObject]])
    {
//        获取uid
        let uid = HMUserAccountViewModel.sharedInstance.userAccount?.uid
        
//        断言
        assert(uid != nil, "没有uid")
        
        let sql = "INSERT INTO T_Status (status_id, status, user_id) VALUES(?, ?, ?)"
//        rollback类似与*stop
        HMSQLiteManager.sharedManager.dbQueue.inTransaction { (db, rollback) -> Void in
//            遍历每条字典
            do
            {
                for dict in status
                {
                    let id = dict["id"] as! Int
                    
//                    微博字典不能直接保存在数据库里
//                    字典->NSData->String
                    let data = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
                    let statusText = String(data: data, encoding: NSUTF8StringEncoding)!
                   try db.executeUpdate(sql, values: [id, statusText, uid!])
                }
                print("保存了:\(status.count)条微博")
            }catch let error as NSError
            {
                print("微博出错了:\(error)")
            }
        }
    }
}
